package com.rbmh.network.utils;

import org.apache.poi.xwpf.usermodel.*;
import java.io.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestV {

    public static void main(String[] args) {
        String filePath = "C:\\Users\\Administrator\\Desktop\\测试.docx";

        System.out.println("开始处理Word文档...");

        // 获取当前的号
        String currentNumber = getCurrentPersonnelNumber(filePath);
        if (currentNumber != null) {
            System.out.println("当前人事调干字号: " + currentNumber);

            // 直接设置为指定号码
            String newNumber = "202"; // 可以设置为任意000-999的数字
            System.out.println("新的调干字号: " + newNumber);

            // 替换为新的号
            replacePersonnelNumber(filePath, currentNumber, newNumber);
        }

        System.out.println("处理完成！");
    }

    /**
     * 获取当前人事调干字号
     */
    public static String getCurrentPersonnelNumber(String filePath) {
        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis)) {

            for (XWPFParagraph para : document.getParagraphs()) {
                String text = para.getText();
                if (text != null && text.contains("新干人事调干字")) {
                    Pattern pattern = Pattern.compile("新干人事调干字（2025）第(\\d{3})号");
                    Matcher matcher = pattern.matcher(text);

                    if (matcher.find()) {
                        return matcher.group(1);
                    }
                }
            }

        } catch (IOException e) {
            System.out.println("读取文件时出错: " + e.getMessage());
        }
        return null;
    }

    /**
     * 精确替换人事调干字号 - 只替换编号部分
     */
    public static void replacePersonnelNumber(String filePath, String oldNumber, String newNumber) {
        if (newNumber.length() != 3) {
            System.out.println("新号码必须是3位数字");
            return;
        }

        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis)) {

            int modifiedCount = 0;

            // 处理所有段落
            for (XWPFParagraph para : document.getParagraphs()) {
                String text = para.getText();
                if (text != null && text.contains("新干人事调干字")) {
                    System.out.println("处理段落: " + text.trim());

                    List<XWPFRun> runs = para.getRuns();

                    // 显示运行结构
                    System.out.println("运行结构:");
                    for (int i = 0; i < runs.size(); i++) {
                        XWPFRun run = runs.get(i);
                        String runText = run.getText(0);
                        if (runText != null) {
                            System.out.println("  运行" + i + ": '" + runText + "'");
                        }
                    }

                    // 查找包含编号数字的运行（在"）第"和"号"之间的数字）
                    boolean foundStart = false;
                    int numberStartIndex = -1;
                    int numberEndIndex = -1;
                    StringBuilder numberBuilder = new StringBuilder();

                    for (int i = 0; i < runs.size(); i++) {
                        XWPFRun run = runs.get(i);
                        String runText = run.getText(0);

                        if (runText != null) {
                            // 查找"）第"标记，表示编号开始
                            if (runText.contains("）第")) {
                                foundStart = true;
                                continue;
                            }

                            // 查找"号"标记，表示编号结束
                            if (runText.contains("号")) {
                                break;
                            }

                            // 在"）第"和"号"之间的运行中查找数字
                            if (foundStart && runText.matches(".*\\d.*")) {
                                if (numberStartIndex == -1) {
                                    numberStartIndex = i;
                                }
                                numberEndIndex = i;

                                // 提取数字部分
                                String digits = runText.replaceAll("[^0-9]", "");
                                numberBuilder.append(digits);

                                // 如果已经收集到3位数字，停止
                                if (numberBuilder.length() >= 3) {
                                    break;
                                }
                            }
                        }
                    }

                    if (numberStartIndex != -1 && numberEndIndex != -1) {
                        System.out.println("编号数字运行范围: " + numberStartIndex + " - " + numberEndIndex);
                        System.out.println("收集到的编号数字: " + numberBuilder.toString());

                        // 只替换编号部分，不替换年份
                        if (replaceNumberInRuns(runs, numberStartIndex, numberEndIndex, newNumber)) {
                            modifiedCount++;
                        }
                    }
                }
            }

            if (modifiedCount > 0) {
                try (FileOutputStream out = new FileOutputStream(filePath)) {
                    document.write(out);
                    System.out.println("成功将编号 " + oldNumber + " 替换为 " + newNumber);
                }
            } else {
                System.out.println("未找到要替换的编号内容");
            }

        } catch (IOException e) {
            System.out.println("处理文件时出错: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 在运行范围内替换数字（只替换数字部分）
     */
    private static boolean replaceNumberInRuns(List<XWPFRun> runs, int startIndex, int endIndex, String newNumber) {
        int newNumberIndex = 0;

        for (int i = startIndex; i <= endIndex && newNumberIndex < newNumber.length(); i++) {
            XWPFRun run = runs.get(i);
            String runText = run.getText(0);

            if (runText != null) {
                // 提取原文本中的非数字部分（保持文字、标点等不变）
                StringBuilder nonDigits = new StringBuilder();
                for (char c : runText.toCharArray()) {
                    if (!Character.isDigit(c)) {
                        nonDigits.append(c);
                    }
                }

                // 计算在这个运行中应该放置的新数字部分
                int digitsInThisRun = countDigits(runText);
                if (digitsInThisRun > 0) {
                    int digitsToPlace = Math.min(digitsInThisRun, newNumber.length() - newNumberIndex);
                    String newDigits = newNumber.substring(newNumberIndex, newNumberIndex + digitsToPlace);

                    // 构建新文本：保留非数字部分，只替换数字部分
                    String newRunText = nonDigits.toString() + newDigits;
                    run.setText(newRunText, 0);

                    System.out.println("运行" + i + "替换: '" + runText + "' -> '" + newRunText + "'");

                    newNumberIndex += digitsToPlace;
                } else {
                    // 如果没有数字，保持原样
                    run.setText(nonDigits.toString(), 0);
                }
            }
        }

        return true;
    }

    /**
     * 计算字符串中的数字数量
     */
    private static int countDigits(String text) {
        int count = 0;
        for (char c : text.toCharArray()) {
            if (Character.isDigit(c)) {
                count++;
            }
        }
        return count;
    }

    /**
     * 精确替换方法 - 根据运行结构直接替换
     */
    public static void preciseReplace(String filePath, String newNumber) {
        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis)) {

            for (XWPFParagraph para : document.getParagraphs()) {
                String text = para.getText();
                if (text != null && text.contains("新干人事调干字")) {
                    List<XWPFRun> runs = para.getRuns();

                    // 根据你的运行结构精确替换
                    // 运行结构: 运行1: '新干人事调干字（', 运行2: '2025', 运行3: '）第', 运行4: '08', 运行5: '1', 运行6: '号'
                    if (runs.size() > 5) {
                        XWPFRun run4 = runs.get(4); // 包含编号前两位
                        XWPFRun run5 = runs.get(5); // 包含编号最后一位

                        String run4Text = run4.getText(0);
                        String run5Text = run5.getText(0);

                        System.out.println("运行4: '" + run4Text + "', 运行5: '" + run5Text + "'");

                        // 只替换数字部分，保持其他内容不变
                        if (run4Text != null && run4Text.matches(".*\\d+.*")) {
                            String newRun4Text = run4Text.replaceAll("\\d+", newNumber.substring(0, 2));
                            run4.setText(newRun4Text, 0);
                            System.out.println("运行4替换: '" + run4Text + "' -> '" + newRun4Text + "'");
                        }

                        if (run5Text != null && run5Text.matches(".*\\d+.*")) {
                            String newRun5Text = run5Text.replaceAll("\\d+", newNumber.substring(2));
                            run5.setText(newRun5Text, 0);
                            System.out.println("运行5替换: '" + run5Text + "' -> '" + newRun5Text + "'");
                        }
                    }
                }
            }

            try (FileOutputStream out = new FileOutputStream(filePath)) {
                document.write(out);
                System.out.println("精确替换完成！");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 最安全的方法 - 直接根据运行索引替换
     */
    public static void safeReplace(String filePath, String newNumber) {
        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis)) {

            for (XWPFParagraph para : document.getParagraphs()) {
                String text = para.getText();
                if (text != null && text.contains("新干人事调干字")) {
                    List<XWPFRun> runs = para.getRuns();

                    // 直接根据运行索引设置（根据你的运行结构）
                    if (runs.size() > 5) {
                        // 运行4应该包含编号的前两位
                        runs.get(4).setText(newNumber.substring(0, 2), 0);
                        // 运行5应该包含编号的最后一位
                        runs.get(5).setText(newNumber.substring(2), 0);

                        System.out.println("直接设置: 运行4='" + newNumber.substring(0, 2) +
                                "', 运行5='" + newNumber.substring(2) + "'");
                    }
                }
            }

            try (FileOutputStream out = new FileOutputStream(filePath)) {
                document.write(out);
                System.out.println("安全替换完成！");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}